package com.ljwy.gun;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.ljwy.gun.adapter.BTAdapter;
import com.ljwy.gun.bean.Device;
import com.ljwy.gun.utils.ToastUtils;
import com.ljwy.gun.utils.cache.ACacheHelper;
import com.rscja.deviceapi.RFIDWithUHFBLE;
import com.rscja.deviceapi.interfaces.ConnectionStatus;
import com.rscja.deviceapi.interfaces.ScanBTCallback;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.ljwy.gun.utils.Constant.BT_NAME;

public class ChooseBTListActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {

    @BindView(R.id.lv)
    ListView lv;
    private Map<String, Integer> devRssiValues = new HashMap<>();
    private ArrayList<Device> mDatas = new ArrayList<>();
    private BTAdapter adapter;
    private static final int REQUEST_ENABLE_BT = 2;
    private BuilderDialog dialog;
    private TextView choose_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_b_t_list);
        ButterKnife.bind(this);
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            ToastUtils.showLong("不支持低功耗蓝牙");
            finish();
        }
        if (!TextUtils.isEmpty(ACacheHelper.getInstance().getString("CPNAME", ""))) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        } else {
            showBluetoothDevice();
        }
        dialog = new BuilderDialog(mContext);
        View view = View.inflate(this, R.layout.dialog_bt, null);
        choose_tv = view.findViewById(R.id.choose_tv);
        view.findViewById(R.id.dismiss_tv).setOnClickListener(this);
        view.findViewById(R.id.go_tv).setOnClickListener(this);
        dialog.setContentView(view).setGrvier(Gravity.CENTER).setOutSideDismiss();
    }

    private void showBluetoothDevice() {
        BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBtAdapter == null) {
            ToastUtils.showShort("蓝牙不可能");
            return;
        }
        if (!mBtAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
            scanLeDevice(true);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == Activity.RESULT_OK) {
                ToastUtils.showShort("蓝牙已打开");
                scanLeDevice(true);
            } else {
                ToastUtils.showShort("蓝牙有问题活没打开");
                finish();
            }
        }
    }

    private void scanLeDevice(boolean flag) {
        if (flag) {
            uhf.startScanBTDevices(new ScanBTCallback() {
                @Override
                public void getDevices(final BluetoothDevice bluetoothDevice, final int rssi, byte[] bytes) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Device myDevice = new Device(bluetoothDevice.getAddress(), bluetoothDevice.getName());
                            addDevice(myDevice, rssi);
                        }
                    });
                }
            });
        }
        adapter = new BTAdapter(this, mDatas);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(this);
    }

    private void addDevice(Device device, int rssi) {
        boolean deviceFound = false;
        for (Device listDev : mDatas) {
            if (listDev.getAddress().equals(device.getAddress())) {
                deviceFound = true;
                break;
            }
        }
        devRssiValues.put(device.getAddress(), rssi);
        if (!deviceFound) {
            mDatas.add(device);
        }

        // 根据信号强度重新排序
        Collections.sort(mDatas, (device1, device2) -> {
            String key1 = device1.getAddress();
            String key2 = device2.getAddress();
            int v1 = devRssiValues.get(key1);
            int v2 = devRssiValues.get(key2);
            return Integer.compare(v2, v1);
        });
        if (!deviceFound) {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Device device = mDatas.get(position);
        uhf.stopScanBTDevices();
        ACacheHelper.getInstance().putString(BT_NAME, device.getAddress());
        choose_tv.setText(String.format("您当前选择蓝牙地址为:%s(请仔细比对)", device.getAddress()));
        dialog.setShow();
    }

    @Override
    public void onStop() {
        super.onStop();
        uhf.stopScanBTDevices();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        uhf.stopScanBTDevices();
    }

    protected void onPause() {
        super.onPause();
        scanLeDevice(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.go_tv:
                Intent intent = new Intent(this, ChooseCpActivity.class);
                startActivity(intent);
                finish();
                dialog.setDismiss();
                break;
            case R.id.dismiss_tv:
                dialog.setDismiss();
                break;
        }
    }
}